import Main from '@/views/Main.vue';
import Cookies from "js-cookie";
import { setStore, getStore, removeStore } from "@/config/storage.js"

// 不作为Main组件的子页面展示的页面单独写，如下
import { page403, page404, loginRouter, page500, locking } from './single'

// 作为Main组件的子页面展示但是不在左侧菜单显示的路由写在otherRouter里
import Other from './other'
export const otherRouter = Other

// 作为Main组件的子页面展示并且在左侧菜单显示的路由写在appRouter里
import Rbac from './rbac'
let findSlideArr = [
    ...Rbac,
]

let sidebarArr = []
let menu = getStore('leftSidebarList')
if (menu != 'undefined') {
    sidebarArr = JSON.parse(menu) || []
}

let userDefinedIDArr = []
findSlideArr.forEach(item => {
    userDefinedIDArr.push(item.name)
})


sidebarArr.forEach((item, index) => {
    if (!userDefinedIDArr.includes(item.name)) {
        delete sidebarArr[index]
    }
})
let formateUndefinedArr = []
sidebarArr.forEach(item => {
    formateUndefinedArr.push(item)
})
if (formateUndefinedArr.length > 0) {
    formateUndefinedArr.forEach(item => {
        let index = userDefinedIDArr.indexOf(item.name)
        item.path = findSlideArr[index].path
        item.icon = findSlideArr[index].icon
        item.perChildren = [...item.subMenu]
        item.children = []
        item.component = Main
        if (item.perChildren.length > 0) {
            item.perChildren.forEach((it, index) => {
                let subIndex = userDefinedIDArr.indexOf(it.name)
                if (subIndex !== -1) {
                    it.icon = findSlideArr[subIndex].icon
                    it.path = findSlideArr[subIndex].path
                    it.component = findSlideArr[subIndex].component
                } else {
                    delete item.perChildren[index]
                }
            })
            item.perChildren.forEach(it => {
                item.children.push(it)
            })

        }
    })

}
// 菜单排序函数 降序
function descend(a, b) {
    return b.sort - a.sort
}
formateUndefinedArr.sort(descend)
if (formateUndefinedArr.length > 0) {
    formateUndefinedArr.forEach((item, index) => {
        if (item.children.length > 0) {
            item.children.sort(descend)
        }
    })
}

export let appRouter = formateUndefinedArr
export const clearAppRouter = () => {
    appRouter = []
}

// 所有上面定义的路由都要写在下面的routers里
export const routers = [
    loginRouter,
    otherRouter,
    locking,
    ...appRouter,
    page500,
    page403,
    page404,
];